package com.cincc.cinccimdemo.ui.me;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.cincc.cinccimdemo.R;
import com.cincc.cinccimdemo.common.Constants;
import com.cincc.cinccimdemo.ui.IMBaseActivity;
import com.cincc.cinccimdemo.ui.main.SetAliasActivity;
import com.cincc.cinccimdemo.widget.OptionItemView;
import com.cincc.im.core.IMSipPhoneCtrl;
import com.cincc.im.model.UserInfoModel;
import com.lqr.imagepicker.ImagePicker;
import com.lqr.imagepicker.bean.ImageItem;

import java.util.ArrayList;

public class MeActivity extends IMBaseActivity {
    private static final String TAG = "UserDetailActivity";

    private static final int MEDIA_ALBUM_CODE = 1201;
    private static final int REQUEST_CODE_PICK_IMAGE = 1202;

    @Override
    protected int contentLayout() {
        return R.layout.activity_user_info;
    }

    TextView titleTextView;
    TextView displayNameTextView;
    TextView accountText;
    ImageView portraitImageView;

    @Override
    protected void bindViews() {
        super.bindViews();
        titleTextView = findViewById(R.id.titleTextView);
        displayNameTextView = findViewById(R.id.displayNameTextView);
        accountText = findViewById(R.id.accountTextView);
        portraitImageView = findViewById(R.id.portraitImageView);
        OptionItemView aliasOptionItemView = findViewById(R.id.aliasOptionItemView);
        OptionItemView qrCodeOptionItemView = findViewById(R.id.qrCodeOptionItemView);
        qrCodeOptionItemView.setVisibility(View.VISIBLE);


        aliasOptionItemView.setOnClickListener(view -> editNickName());
        qrCodeOptionItemView.setOnClickListener(view -> qrCode());
        portraitImageView.setOnClickListener(view -> editAvatar());

        refreshUI();
    }

    private void refreshUI() {
        titleTextView.setText(Constants.userInfo.nickName);
        displayNameTextView.setText("ID:" + Constants.userInfo.userId);
        accountText.setVisibility(View.GONE);

        Glide.with(this).load(Constants.userInfo.avatarUrl).placeholder(R.mipmap.avatar_def)
                .transforms(new CenterCrop(), new RoundedCorners(15))
                .into(portraitImageView);
    }

    private void editNickName() {
        Intent i = new Intent(this, SetAliasActivity.class);
        startActivity(i);
    }

    private void qrCode() {
        QRCodeActivity.startQrcode(this, 0, Constants.userInfo.userId);
    }

    private void editAvatar() {
        String[] permissions;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permissions = new String[]{
                    Manifest.permission.READ_MEDIA_IMAGES,
            };
        } else {
            permissions = new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
            };
        }
        for (String permission : permissions) {
            if (checkCallingOrSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(permissions, MEDIA_ALBUM_CODE);
                return;
            }
        }
        ImagePicker.picker().pick(this, REQUEST_CODE_PICK_IMAGE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MEDIA_ALBUM_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                ImagePicker.picker().pick(this, REQUEST_CODE_PICK_IMAGE);
            } else {
                Toast.makeText(this, "请打卡相册权限", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PICK_IMAGE && resultCode == Activity.RESULT_OK) {
            ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
            if (images == null || images.isEmpty()) {
                Toast.makeText(this, "更新头像失败: 选取文件失败 ", Toast.LENGTH_SHORT).show();
                return;
            }
            String imagePath = images.get(0).path;
            Log.e(TAG, "onActivityResult:imagePath = " + imagePath);
            IMSipPhoneCtrl.getInstance().updateUserAvatar(imagePath, imResponse -> {
                String result = imResponse.getCode() == 0 ? "修改成功" : imResponse.getMsg();
                IMSipPhoneCtrl.getInstance().getPersonInfo(imResponse1 -> {
                    Constants.userInfo = (UserInfoModel) imResponse1.getData();
                    runOnUiThread(this::refreshUI);
                });
                runOnUiThread(() -> Toast.makeText(MeActivity.this, result, Toast.LENGTH_SHORT).show());
            });
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
}